package cn.phecda.boot.job.xxljob.handler;

import cn.phecda.boot.common.lang.util.ShellUtils;
import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;

import java.util.Optional;

/**
 * <p>命令行任务</p>
 *
 * @author wanpinwei
 */
@Slf4j
public class ShellJobHandler extends BaseJobHandler {

    @XxlJob("shellJobHanlder")
    public void shellJobHanlder() {
        Optional<String> commandOpt = getParam();
        if (commandOpt.isEmpty()) {
            return;
        }

        try {
            String command = commandOpt.get();
            XxlJobHelper.log("Execute shell command:" + command);
            int exitValue = ShellUtils.execute(command, XxlJobHelper::log);
            if (exitValue != 0) {
                XxlJobHelper.handleFail("Shell command execution failed:" + exitValue);
            } else {
                XxlJobHelper.log("Execute shell command successfully");
            }
        } catch (Exception e) {
            XxlJobHelper.handleFail(e.getMessage());
        }


    }
}
